#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By : cdj <e4ting@qq.com> 2021-07-14 17:57:18
"""
from flask_restful import Resource
from flask         import redirect,request,make_response

from urllib.parse import urlparse

from e4ting import util,log
from e4ting.cache import UUIDCache
from models.mongos import DB
from models.mysqls import db,ModelUuids
# from e4ting.task   import Anon

from core.device import UUID

class WebBotUid(Resource):
    def __init__(self, *args, **kwargs):
        self.is_new = False
        super(WebBotUid, self).__init__(*args, **kwargs)

    def do_hook(self, uuid):
        host = request.host
        ip = request.remote_addr
        referer = request.headers.get('Referer')
        if referer:
            domain = urlparse(referer).netloc
        else:
            domain = host

        if hasattr(self, "is_new") and self.is_new:
            Anon().node_registe_callback(host=host, referer=domain, ip=ip, uuid=uuid)
        else:
            log.info(dict(request.headers, domain=domain, url=request.url))
            Anon().node_view_api(uuid, ip, dict(request.headers, domain=domain, url=request.url))

    # 傻逼钉钉，会一直探测这个接口
    # def get(self, id=None):
    #     """创建玩家ID"""
    #     uuid = id or request.args.get("uuid", None)
    #     if not uuid:
    #         return {
    #             "code" : 400
    #         }
    #     data = self.calc_uid(uuid)
    #     DB.clients[data] = dict(request.headers, uuid=uuid, ip=request.remote_addr, uptime=util.now())
    #     self.do_hook(data)
    #     return {
    #         "code" : 200,
    #         "data"  : data,
    #     }

    def save(self, uid, info):
        item = ModelUuids(
            uuid=uid,
            info=info,
            ip=request.remote_addr,
            agent=request.headers.get('User-Agent', ""),
            )
        db.session.add(item)

    def post(self, id=None):
        """计算客户端唯一ID"""
        # request.json
        info = id or request.json.get("info", None)
        log.info(request.json)
        uID = UUID(info)
        uid = uID.get()
        self.save(uid, info)
        # DB.clients[data] = dict(request.headers, uuid=uuid, ip=request.remote_addr, uptime=util.now())
        # self.do_hook(data)
        return {
            "code" : 200,
            "data"  : uid,
        }

if __name__ == '__main__':
    WebBotClient().calc_uid("test")
